package com.fsnmt.maizhuanbao.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SystemUtils {
    private static final String[] PHONES_PROJECTION = new String[]{
            Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID};
    private static final int PHONES_NUMBER_INDEX = 1;



    /**获取状态栏的高度*/
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen","android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }



    /**
     * 获取系统的versionCode
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();//context为当前Activity上下文
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取系统的versionCode
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageManager pm = context.getPackageManager();//context为当前Activity上下文
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 隐藏输入法，此方法输入开关方法，即显示隐藏双切换，所有时候需要判断当前的输入法状态
     *
     * @param context
     */
    public static void hideKeybord(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 隐藏输入法，使用时传递需要隐藏的view
     *
     * @param context
     * @param view
     */
    public static void hideKeybord(Context context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getApplicationContext().
                getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void hideKeybord(Activity context) {
        try {
            InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (context.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                if (context.getCurrentFocus() != null)
                    manager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
        }
    }

    public static void switchKeyBoard(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        //得到InputMethodManager的实例
//		if (imm.isActive()) {
        //如果开启
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
        //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
//		}
    }


    /**
     * 显示键盘，并将输入法焦点放到指定view上。
     *
     * @param context
     * @param v       获取输入内容的view
     */
    public static void showKeyboard(Context context, View v) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 判断输入发是否打开
     *
     * @param context
     * @return 若返回true，则表示输入法打开
     */
    public static boolean isKeyboardShowing(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();
    }

    /**
     * 检测sdcard是否已被加载
     *
     * @return
     */
    public static boolean isSDCardMounted() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 把图片保存到系统相册
     *
     * @param context
     * @param bm       图片
     * @param fileName 文件名
     * @return 是否成功。
     */
    public static boolean savePhotoToSystemGallery(Context context, Bitmap bm,
                                                   String fileName) {
        if (isSDCardMounted() && null != bm) {
            try {
                ContentResolver cr = context.getContentResolver();
                String url = MediaStore.Images.Media.insertImage(cr, bm,
                        fileName, "");
                if (!TextUtils.isEmpty(url)) {
                    context.sendBroadcast(new Intent(
                            Intent.ACTION_MEDIA_MOUNTED,
                            Uri.parse("file://"
                                    + Environment.getExternalStorageDirectory())));
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 把图片保存到系统相册
     *
     * @param context
     * @param fromFile 要保存的图片路径
     * @param fileName
     * @return
     */
    public static boolean savePhotoToSystemGallery(Context context,
                                                   String fromFile, String fileName) {
        if (isSDCardMounted()) {
            Bitmap bm = null;
            try {
                bm = BitmapFactory.decodeFile(fromFile);
                if (null != bm)
                    return savePhotoToSystemGallery(context, bm, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /***
     * install new version apk
     *
     * @param context
     * @param apkPath /xxx/xx/xxx.apk
     */
    public static void installApk(Context context, String apkPath) {
        if (FileUtils.isExist(apkPath)) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");
            context.startActivity(i);
        }

    }

    /**
     * 删除收件箱中号码为number的所有短信
     *
     * @param context
     * @param number
     */
    public static void deleteSMS(Context context, String number) {
        try {
            ContentResolver CR = context.getContentResolver();
            Uri uriSms = Uri.parse("content://sms/inbox");
            Cursor c = CR.query(uriSms, new String[]{"_id", "thread_id", "address"}
                    , "type = '1' and address = '" + number + "' ", null, null);
            if (null != c && c.moveToFirst()) {
                do {
                    // Delete SMS
                    int thread_id_dex = c.getColumnIndex("thread_id");
                    long threadId = c.getLong(thread_id_dex);
                    CR.delete(Uri.parse("content://sms/conversations/" + threadId), null, null);
                } while (c.moveToNext());
                c.close();
            }
        } catch (Exception e) {
            Log.d("deleteSMS", "Exception:: " + e);
        }
    }


    public static boolean getContactsReadAndWritePermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.WRITE_CONTACTS);
//            getPermission(activity, new String[] {Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS}, RequestCode.REQUEST_CODE_CONTACT);
            getPermission(context, new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, RequestCode.REQUEST_CODE_CONTACT);
            return shouldShow;
        } else
            return false;
    }

    public static boolean checkContactsPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= 23)
            return checkPermission(activity, Manifest.permission_group.CONTACTS);
        else
            return true;
    }

    public static List<String> getPhoneList(Context context, Map<String, String> map) {
        if (null == map) {
            map = new HashMap<>();
        }

        ArrayList<String> contacts = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String phoneNumber = cursor.getString(PHONES_NUMBER_INDEX);// get phone
                if (TextUtils.isEmpty(phoneNumber)) {
                    continue;
                }
                phoneNumber = phoneNumber.replace(" ", "");
                phoneNumber = phoneNumber.replace("-", "");
                if (phoneNumber.length() != 11 || !CommonDataVerify.isMobilePhoneNo(phoneNumber)) {// IF IS NULL CONTINUE
                    continue;
                }
                String contactName = cursor.getString(0);// get name
                if (TextUtils.isEmpty(contactName)) {
                    contactName = phoneNumber;
                }
                contacts.add(phoneNumber);
                map.put(phoneNumber, contactName);
            }
            cursor.close();
        }
        return contacts;
    }


    public static boolean isRuningBackgroud(Context context, String pageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(pageName) || info.baseActivity.getPackageName().equals(pageName)) {
                isAppRunning = true;
                Log.i("TAG", info.topActivity.getPackageName() + "," + info.baseActivity.getPackageName());
                break;
            }
        }
        return isAppRunning;
    }

    public static boolean checkSMSPermission(Context context) {
        if (Build.VERSION.SDK_INT < 23)
            return true;
        return checkPermission(context, Manifest.permission_group.SMS);
    }

    public static boolean getSMSPermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.READ_CONTACTS);
            getPermission(context, new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, RequestCode.REQUEST_CODE_SMS);
            return shouldShow;
        } else
            return false;
    }

    public static boolean getStoragePermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            getPermission(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, RequestCode.REQUEST_CODE_STORAGE);
            return shouldShow;
        } else
            return false;
    }

    public static boolean checkStoragePermission(Context context) {
        return checkPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    public static boolean getLuYinPermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.RECORD_AUDIO);
            getPermission(context, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.MODIFY_AUDIO_SETTINGS}, RequestCode.REQUEST_CODE_LUYIN);
            return shouldShow;
        } else
            return false;
    }

    public static boolean checkLuYinPermission(Context context) {
        return checkPermission(context, Manifest.permission.RECORD_AUDIO);
    }


    public static boolean checkLocationPermission(Context context) {
        if (Build.VERSION.SDK_INT >= 23)
            return checkPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
        else
            return true;
    }

    public static boolean getLocationPermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            getPermission(context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode.REQUEST_CODE_LOCATION);
            return shouldShow;
        } else
            return false;
    }

    public static boolean getLocationPermission(Fragment fragment){
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(fragment.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
            fragment.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode.REQUEST_CODE_LOCATION);
            return shouldShow;
        }else
            return false;
    }

    public static boolean checkPhoneStatusPermission(Context context) {
        if (Build.VERSION.SDK_INT >= 23)
            return checkPermission(context, Manifest.permission.READ_PHONE_STATE);
        else
            return true;
    }
    public static boolean getPhoneStatusPermission(Fragment fragment){
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(fragment.getActivity(), Manifest.permission.READ_PHONE_STATE);
            fragment.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, RequestCode.REQUEST_CODE_PHONE_STATUS);
            return shouldShow;
        }else
            return false;
    }

    public static boolean getCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean shouldShow = ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.CAMERA);
            getPermission(context, new String[]{Manifest.permission.CAMERA}, requestCode);
            return shouldShow;
        } else
            return false;
    }

    public static boolean checkCameraPermission(Context context) {
        return checkPermission(context, Manifest.permission.CAMERA);
    }

    public static boolean checkPermission(Context context, String permission) {
        if (Build.VERSION.SDK_INT < 23)
            return true;
        int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, permission);
        return checkCallPhonePermission == PackageManager.PERMISSION_GRANTED;
    }

//    public static boolean checkPermissionDenied(Context context, String permission) {
//        int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, permission);
//        return checkCallPhonePermission == PackageManager.PERMISSION_DENIED;
//    }


//    public static int checkAutoLocationPermission(Context context) {
//            if (Build.VERSION.SDK_INT >= 23) {
//                int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
//                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
//                }
//            }
//    }



//    public static boolean checkPermission(Context context, String permission) {
//        boolean Result = false;
//        if (Build.VERSION.SDK_INT >= 23) {
//            try {
//                Class clazz = Class.forName("android.content.Context");
//                Method method = clazz.getMethod("checkSelfPermission", String.class);
//                int rest = (Integer) method.invoke(context, permission);
//                if (rest == PackageManager.PERMISSION_GRANTED) {
//                    Result = true;
//                } else {
//                    Result = false;
//                }
//            } catch (Exception e) {
//                Result = false;
//            }
//        } else {
//            PackageManager pm = context.getPackageManager();
//            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
//                Result = true;
//            }
//        }
//        return Result;
//    }
//
//    public static boolean checkPermissionDenied(Context context, String permission) {
//        boolean Result = false;
//        if (Build.VERSION.SDK_INT >= 23) {
//            try {
//                Class clazz = Class.forName("android.content.Context");
//                Method method = clazz.getMethod("checkSelfPermission", String.class);
//                int rest = (Integer) method.invoke(context, permission);
//                if (rest == PackageManager.PERMISSION_DENIED) {
//                    Result = true;
//                } else {
//                    Result = false;
//                }
//            } catch (Exception e) {
//                Result = false;
//            }
//        } else {
//            PackageManager pm = context.getPackageManager();
//            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_DENIED) {
//                Result = true;
//            }
//        }
//        return Result;
//    }








    public static void getPermission(Activity context, String[] permissions, int resultCode) {
        ActivityCompat.requestPermissions(context, permissions, resultCode);
    }

    public static boolean callPhone(String number, Activity context) {
        if (Build.VERSION.SDK_INT < 23) {
            call(number, context);
            return true;
        }

        int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.CALL_PHONE}, RequestCode.REQUEST_CODE_ASK_CALL_PHONE);
            return false;
        } else {
            call(number, context);
            return true;
        }
    }

    public static boolean callPhone(String number, Fragment fragment) {
        if (Build.VERSION.SDK_INT < 23) {
            call(number, fragment.getActivity());
            return true;
        }
        int checkCallPhonePermission = ContextCompat.checkSelfPermission(fragment.getActivity(), Manifest.permission.CALL_PHONE);
        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
            fragment.requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, RequestCode.REQUEST_CODE_ASK_CALL_PHONE);
            return false;
        } else {
            call(number, fragment.getActivity());
            return true;
        }
    }

    public static void call(String number, Activity context) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
        context.startActivity(intent);
    }

    /**
     * 这个方法有缺陷，因为个别推送用importance是没有效果的
     * @param context
     * @return
     */
    public static boolean isBackGround(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
                BACKGROUND=400 EMPTY=500 FOREGROUND=100
                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                 */
                Log.i(context.getPackageName(), "此appimportace =" + appProcess.importance + ",context.getClass().getName()=" + context.getClass().getName());
                if (appProcess.importance!= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台" + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台" + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }



    public static  void  skipAppSetting(Activity activity){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT >= 9){
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if(Build.VERSION.SDK_INT <= 8){
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        activity.startActivity(intent);
    }

    public static boolean isBackGrounded(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (int i = 0;i<appProcesses.size();i++) {
            if (appProcesses.get(i).processName.equals(context.getPackageName())) {
                if(i!=0) {
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    }

    public interface RequestCode {
        int REQUEST_CODE_ASK_CALL_PHONE = 0x81;
        int REQUEST_CODE_SMS = 0x82;
        int REQUEST_CODE_CONTACT = 0x83;
        int REQUEST_CODE_STORAGE = 0x84;
        int REQUEST_CODE_CAMERA = 0x85;
        int REQUEST_CODE_LOCATION = 0x86;
        int REQUEST_CODE_LOCATION_TEMP = 0x88;
        int REQUEST_CODE_LOCATION_CHAT = 0x89;
        int REQUEST_CODE_LUYIN = 0x87;
        int REQUEST_CODE_PHONE_STATUS = 0x8A;

    }
}
